<?php
namespace app\index\controller;
use think\App;
use think\Controller;
use app\index\model\Redis;
use think\facade\Session;
use think\Db;

class Index extends Controller
{
    public function index(){
        return $this->redirect('/login');
    }

    // 聊天页面
    public function chat()
    {

        $websocket = config('swoole.websocket_url');
        $uid = Session::get('user_info.uid');
        if(!$uid){
            return $this->redirect('/login');
        }

        return $this->fetch('./chat',['uid'=>$uid,'websocket'=>$websocket]);
    }

    // 发布朋友圈
    public function createFriendCircle()
    {
        $data['content'] = $this->request->param('content','');
        $data['images']  = json_encode($this->request->param('imgs'));
        $data['uid']     = $this->request->param('uid');
        $data['create_time'] = time();
        if(!Db::name('user')->where('id',$data['uid'])->field('id')->find()) return json(['code'=>400,'msg'=>'该用户不存在，无法发送']);
        if(empty($data['content']) && empty($data['images'])) return json(['code'=>400,'msg'=>'请输入要发送的内容']);
        // 插入数据
        $res = Db::name('friend_circle')->insertGetId($data);
        if($res){
            $info = Db::name('friend_circle')
                ->alias('f')
                ->join('yqy_user u','f.uid = u.id')
                ->where('f.id',$res)->field('f.id,f.uid,create_time,images,content,zan,u.username,u.avatar')->find();
            return json(['code'=>200,'msg'=>'发送成功','data'=>$info]);
        } else {
            return json(['code'=>400,'msg'=>'发布失败']);
        }
    }

    // 获取最新的朋友圈10条
    public function getCircleList()
    {
        $circle_list = Db::name('friend_circle')
            ->alias('f')
            ->join('yqy_user u','f.uid = u.id')
            ->where('f.status',1)->field('f.id,f.uid,create_time,images,content,zan,u.username,u.avatar')->order('f.id desc')->select();
        foreach ($circle_list as $key => $value){
            $circle_list[$key]['images'] = json_decode($value['images'],true);
        }
        return json(['code'=>200,'msg'=>'获取成功','data'=>$circle_list]);
    }

    // 根据fd获取聊天数据
    public function getMsgArr(){
        $key = $this->request->param('key');
        $e_key = $this->request->param('e_key');
        $is_all = $this->request->param('is_all') ?: 0;
        $key = Redis::key_exists($key) ? $key : $e_key;
        if($is_all){
            $data = Redis::lrange($key,0,-1) ?: [];
        } else {
            $data = Redis::lrange($key,0,0) ?: [];
        }
        return json_encode(['code'=>200,'data'=>$data]);
    }

    // 根据房间ID获取数据
    public function getRoomMsgArr()
    {
        $key = $this->request->param('key');
        $is_all = $this->request->param('is_all') ?: 0;
        if($is_all){
            $data = Redis::lrange($key,0,-1) ?: [];
        } else {
            $data = Redis::lrange($key,0,0) ?: [];
        }
        return json_encode(['code'=>200,'data'=>$data]);
    }

    // 图片上传
    public function upload_img()
    {
        $type = $this->request->param('type') ?: 0;
        // 获取上传文件
        if($type == 1){
            $file = request() -> file('circle_img_select');
            // 验证图片,并移动图片到框架目录下。
            $info = $file -> validate(['size' => 102400,'ext' => 'jpg,png,jpeg','type' => 'image/jpeg,image/png']) -> move('public/uploads/circle');
            if($info){
                // $info->getExtension();         // 文件扩展名
                $mes = '/uploads/circle/'.$info->getSaveName();      // 文件名
                return json_encode(['code'=>200,'msg'=>$mes]);
            }else{
                // 文件上传失败后的错误信息
                $mes = $file->getError();
                return json_encode(['code'=>400,'msg'=>$mes]);
            }
        } else {
            $file = request() -> file('getImg');
            // 验证图片,并移动图片到框架目录下。
            $info = $file -> validate(['size' => 102400,'ext' => 'jpg,png,jpeg','type' => 'image/jpeg,image/png']) -> move('public/uploads/chat');
            if($info){
                // $info->getExtension();         // 文件扩展名
                $mes = '/uploads/chat/'.$info->getSaveName();      // 文件名
                return json_encode(['code'=>200,'msg'=>$mes]);
            }else{
                // 文件上传失败后的错误信息
                $mes = $file->getError();
                return json_encode(['code'=>400,'msg'=>$mes]);
            }
        }
    }

    // 点赞
    public function click_zan()
    {
        $data['uid'] = $this->request->param('uid');
        $data['cir_id'] = $this->request->param('cir_id');
        $data['create_time'] = time();

        // 判断是否点过赞
        if(Db::name('click_zan')->where(['uid'=>$data['uid'],'cir_id'=>$data['cir_id']])->field('id')->find()){
           return json(['code'=>400,'msg'=>'您已经点过赞了']);
        } else {
            $res = Db::name('click_zan')->insert($data);
            if($res){
                Db::name('friend_circle')->where('id',$data['cir_id'])->setInc('zan');
                $zan = Db::name('friend_circle')->where('id',$data['cir_id'])->value('zan');
                return json(['code'=>200,'msg'=>'点赞成功','data'=>$zan]);
            } else {
                return json(['code'=>400,'msg'=>'点赞失败']);
            }

        }

    }

    // 朋友圈评论
    public function click_ping()
    {
        $data['content'] = $this->request->param('content');
        $data['uid'] = $this->request->param('uid');
        $data['circle_id'] = $this->request->param('cir_id');
        $res = Db::name('circle_comment')->insertGetId($data);
        if($res){
            $info = Db::name('circle_comment')->alias('a')
                ->join('yqy_user u','a.uid = u.id')
                ->where(['a.id'=>$res,'a.status'=>1])->field('a.id,a.uid,circle_id,content,fid,u.avatar,u.username')->find();
            return json(['code'=>200,'msg'=>'评论成功','data'=>$info]);
        } else {
            return json(['code'=>400,'msg'=>'评论失败']);
        }
    }

    // 获取评论
    public function getComment()
    {
        $cir_id = $this->request->param('cir_id');
        $circle_comment = Db::name('circle_comment')->alias('a')
                        ->join('yqy_user u','a.uid = u.id')
                        ->where(['circle_id'=>$cir_id,'a.status'=>1])->field('a.id,a.uid,circle_id,content,fid,u.avatar,u.username')->order('a.id desc')->select();
        return json(['code'=>200,'msg'=>'获取成功','data'=>$circle_comment]);
    }

    // 删除朋友圈
    public function del_circle()
    {
        $cir_id = $this->request->param('cir_id');
        $res = Db::name('friend_circle')->where('id',$cir_id)->delete();
        if($res){
            // 删除点赞记录
            Db::name('click_zan')->where('cir_id',$cir_id)->delete();
            Db::name('circle_comment')->where('circle_id',$cir_id)->delete();
            return json(['code'=>200,'msg'=>'删除成功']);
        } else {
            return json(['code'=>400,'msg'=>'删除失败']);
        }
    }

    // 清除所有redis的缓存
    public function del_redis_key()
    {
        $keys = Redis::keys('*');
        foreach ($keys as $k=>$v){
            if($k !== 'user_13372510395'){
                Redis::del($v);
            }
            continue;
        }
        dump(Redis::keys('*'));
    }

}
